package top.clydezhou.lab.demo.springcloud.client.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import top.clydezhou.lab.demo.springcloud.client.config.DemoApiConstants;
import top.clydezhou.lab.demo.springcloud.client.config.ServiceConfig;
import top.clydezhou.lab.demo.springcloud.client.service.IConsumerDemoClient;

import javax.annotation.Resource;

@RestController
public class DemoController {
    @Resource
    ServiceConfig serviceConfig;
    /**
     * 负载均衡客户端
     */
    @Autowired
    LoadBalancerClient loadBalancerClient;

    /**
     * rest 接口调用模板工具类。
     */
    @Autowired
    RestTemplate restTemplate;

    /**
     * 使用 ribbon 进行负载均衡的 rest template
     */
    @Resource(name = "ribbonRestTemplate")
    RestTemplate ribbonRestTemplate;

    /**
     * 服务发现客户端
     */
    @Autowired
    DiscoveryClient discoveryClient;

    /**
     * 通过fegin接口，封装远程调用
     */
    @Resource
    IConsumerDemoClient consumerDemoClient;

    @GetMapping("/feignDemo")
    public String feignDemo() {
        return consumerDemoClient.consumer();
    }

    /**
     * 负载均衡演示
     *
     * @return
     */
    @GetMapping("/consumer")
    public String loadBalancerClientDemo() {
        ServiceInstance serviceInstance = loadBalancerClient.choose(serviceConfig.getApplicationName());
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + DemoApiConstants.DISCOVER_CLIENT_API;
        System.out.println(url);
        return restTemplate.getForObject(url, String.class);
    }

    /**
     * 使用ribbon负载均衡的restTemplate，默认解析服务地址
     *
     * @return
     */
    @GetMapping("/ribbon-consumer")
    public String ribbonLoadBalancerClientDemo() {
        String url = "http://" + serviceConfig.getApplicationName() + DemoApiConstants.DISCOVER_CLIENT_API;
        System.out.println(url);
        return ribbonRestTemplate.getForObject(url, String.class);
    }

    /**
     * 普通的服务发现客户端，获取注册中心所有的服务
     *
     * @return
     */
    @GetMapping(DemoApiConstants.DISCOVER_CLIENT_API)
    public String dc() {
        String services = "Services: " + discoveryClient.getServices();
        System.out.println(services);
        return services;
    }
}
